package com.sfx.算法专题.链表.链表相加;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-08-03
 * Time: 22:18
 */
public class Code_1_addTwoNumbers {
    static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    static class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode dummy = new ListNode(-1);
            ListNode tmp = dummy;
            int sum = 0;
            int carry = 0;
            //1.同时遍历两个链表,进行累加操作
            while(l1 != null || l2 != null) {
                int val1 =  l1 == null ? 0 : l1.val;
                int val2 =  l2 == null ? 0 : l2.val;
                sum = val1 + val2;
                ListNode node = new ListNode((sum+carry)%10);
                carry = (sum+carry) / 10;
                tmp.next = node;
                tmp = tmp.next;
                if(l1!=null) l1 = l1.next;
                if(l2!=null) l2 = l2.next;
            }
            if(carry > 0) tmp.next = new ListNode(carry);
            return dummy.next;
        }
    }
}